package de.tu_darmstadt.gdi1.battleship.net;

import java.io.*;
import java.net.*;

public class BattleshipServer {

	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;

	public ServerSocket getProviderSocket() {
		return providerSocket;
	}

	public void setProviderSocket(ServerSocket providerSocket) {
		this.providerSocket = providerSocket;
	}

	public Socket getConnection() {
		return connection;
	}

	public void setConnection(Socket connection) {
		this.connection = connection;
	}

	public ObjectOutputStream getOut() {
		return out;
	}

	public void setOut(ObjectOutputStream out) {
		this.out = out;
	}

	public ObjectInputStream getIn() {
		return in;
	}

	public void setIn(ObjectInputStream in) {
		this.in = in;
	}

	public BattleshipServer() {
	}

	public void init() {
		try {
			// 1. creating a server socket
			providerSocket = new ServerSocket(1337, 1);
			// 2. Wait for connection
			System.out.println("Waiting for connection");
			connection = providerSocket.accept();
			System.out.println("Connection received from "
					+ connection.getInetAddress().getHostName());
			// 3. get Input and Output streams
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			
		} catch (IOException e) {
			e.printStackTrace();}
	}

	

	public void sendObject(NetObject o) {
		try {
			out.writeObject(o);
			out.flush();
			System.out.println("server>" + o);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public NetObject recieveObject(){
		NetObject no = null;
		try {
			no = (NetObject) in.readObject();
			System.out.println("client>" + no);
		} catch (ClassNotFoundException e) {
			System.err.println("Data received in unknown format");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return no;
	}
		  
	public void close(){
		try {
			in.close();
			out.close();
			providerSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]) {
		BattleshipServer server = new BattleshipServer();
			server.init();
//			while(!server.providerSocket.isClosed()){
				server.recieveObject();
//			}
	}
}
